import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Space, Popconfirm, Select, DatePicker, Switch, InputNumber } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';
import './ArticleManagement.css';

const { RangePicker } = DatePicker;
const { Option } = Select;

const ArticleManagement = () => {
  const [articles, setArticles] = useState([]);
  const [categories, setCategories] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingArticle, setEditingArticle] = useState(null);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [dateRange, setDateRange] = useState(null);

  // 模拟数据加载
  useEffect(() => {
    // 这里应该是从API获取数据
    const mockArticles = [
      {
        id: 1,
        title: 'React入门教程',
        content: 'React是一个用于构建用户界面的JavaScript库...',
        categoryId: 3,
        categoryName: '前端开发',
        author: '管理员',
        status: 'published',
        views: 1250,
        likes: 89,
        comments: 23,
        publishDate: '2024-01-15',
        createTime: '2024-01-10 10:30:00',
        updateTime: '2024-01-15 14:20:00',
        isTop: false,
        isRecommend: true
      },
      {
        id: 2,
        title: 'Vue.js最佳实践',
        content: 'Vue.js是一个渐进式JavaScript框架...',
        categoryId: 3,
        categoryName: '前端开发',
        author: '管理员',
        status: 'draft',
        views: 0,
        likes: 0,
        comments: 0,
        publishDate: null,
        createTime: '2024-01-12 09:15:00',
        updateTime: '2024-01-12 09:15:00',
        isTop: false,
        isRecommend: false
      },
      {
        id: 3,
        title: 'Node.js后端开发',
        content: 'Node.js是一个基于Chrome V8引擎的JavaScript运行环境...',
        categoryId: 4,
        categoryName: '后端开发',
        author: '管理员',
        status: 'published',
        views: 890,
        likes: 67,
        comments: 15,
        publishDate: '2024-01-08',
        createTime: '2024-01-05 16:45:00',
        updateTime: '2024-01-08 11:30:00',
        isTop: true,
        isRecommend: true
      }
    ];

    const mockCategories = [
      { id: 1, name: '技术文章' },
      { id: 2, name: '生活随笔' },
      { id: 3, name: '前端开发' },
      { id: 4, name: '后端开发' }
    ];

    setArticles(mockArticles);
    setCategories(mockCategories);
  }, []);

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          {record.isTop && <span style={{ color: '#ff4d4f', fontSize: '12px' }}>[置顶]</span>}
          {record.isRecommend && <span style={{ color: '#52c41a', fontSize: '12px', marginLeft: 4 }}>[推荐]</span>}
        </div>
      ),
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      render: (text) => <span style={{ color: '#1890ff' }}>{text}</span>,
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          published: { text: '已发布', color: '#52c41a' },
          draft: { text: '草稿', color: '#faad14' },
          archived: { text: '已归档', color: '#8c8c8c' }
        };
        const statusInfo = statusMap[status] || { text: '未知', color: '#ff4d4f' };
        return <span style={{ color: statusInfo.color, fontWeight: 500 }}>{statusInfo.text}</span>;
      },
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      key: 'views',
      sorter: (a, b) => a.views - b.views,
    },
    {
      title: '点赞数',
      dataIndex: 'likes',
      key: 'likes',
      sorter: (a, b) => a.likes - b.likes,
    },
    {
      title: '评论数',
      dataIndex: 'comments',
      key: 'comments',
      sorter: (a, b) => a.comments - b.comments,
    },
    {
      title: '发布时间',
      dataIndex: 'publishDate',
      key: 'publishDate',
      render: (date) => date || '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="default" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这篇文章吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="是"
            cancelText="否"
          >
            <Button 
              type="danger" 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingArticle(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingArticle(record);
    form.setFieldsValue({
      ...record,
      publishDate: record.publishDate ? moment(record.publishDate) : null
    });
    setIsModalVisible(true);
  };

  const handleView = (record) => {
    message.info('查看文章功能开发中...');
  };

  const handleDelete = (id) => {
    // 这里应该是调用API删除
    setArticles(articles.filter(article => article.id !== id));
    message.success('删除成功');
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      setLoading(true);
      setTimeout(() => {
        if (editingArticle) {
          // 编辑现有文章
          const updatedArticles = articles.map(article => 
            article.id === editingArticle.id ? { 
              ...values, 
              id: editingArticle.id,
              publishDate: values.publishDate ? values.publishDate.format('YYYY-MM-DD') : null,
              updateTime: moment().format('YYYY-MM-DD HH:mm:ss')
            } : article
          );
          setArticles(updatedArticles);
          message.success('更新成功');
        } else {
          // 添加新文章
          const newArticle = {
            ...values,
            id: Date.now(), // 临时ID
            views: 0,
            likes: 0,
            comments: 0,
            publishDate: values.publishDate ? values.publishDate.format('YYYY-MM-DD') : null,
            createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            updateTime: moment().format('YYYY-MM-DD HH:mm:ss')
          };
          setArticles([...articles, newArticle]);
          message.success('添加成功');
        }
        setIsModalVisible(false);
        form.resetFields();
        setLoading(false);
      }, 1000);
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const getCategoryOptions = () => {
    return categories.map(cat => (
      <Option key={cat.id} value={cat.id}>{cat.name}</Option>
    ));
  };

  const filteredArticles = articles.filter(article => {
    const matchesSearch = !searchText || 
      article.title.toLowerCase().includes(searchText.toLowerCase()) ||
      article.content.toLowerCase().includes(searchText.toLowerCase());
    
    const matchesCategory = !selectedCategory || article.categoryId === selectedCategory;
    
    const matchesDateRange = !dateRange || 
      (article.publishDate && 
        moment(article.publishDate).isBetween(dateRange[0], dateRange[1], null, '[]'));
    
    return matchesSearch && matchesCategory && matchesDateRange;
  });

  return (
    <div className="article-management">
      <div className="article-header">
        <div className="search-filters">
          <Input
            placeholder="搜索文章标题或内容"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 300, marginRight: 16 }}
          />
          <Select
            placeholder="选择分类"
            value={selectedCategory}
            onChange={setSelectedCategory}
            allowClear
            style={{ width: 150, marginRight: 16 }}
          >
            {getCategoryOptions()}
          </Select>
          <RangePicker
            placeholder={['开始日期', '结束日期']}
            value={dateRange}
            onChange={setDateRange}
            style={{ marginRight: 16 }}
          />
        </div>
        <div className="article-actions">
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加文章
          </Button>
        </div>
      </div>

      <Table 
        columns={columns} 
        dataSource={filteredArticles} 
        rowKey="id"
        pagination={{
          total: filteredArticles.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
        }}
        className="article-table"
      />

      <Modal
        title={editingArticle ? '编辑文章' : '添加文章'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={800}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="title"
            label="文章标题"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>
          
          <Form.Item
            name="categoryId"
            label="文章分类"
            rules={[{ required: true, message: '请选择文章分类' }]}
          >
            <Select placeholder="请选择文章分类">
              {getCategoryOptions()}
            </Select>
          </Form.Item>

          <Form.Item
            name="content"
            label="文章内容"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <Input.TextArea rows={8} placeholder="请输入文章内容" />
          </Form.Item>

          <Form.Item
            name="publishDate"
            label="发布时间"
          >
            <DatePicker 
              placeholder="选择发布时间" 
              style={{ width: '100%' }}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>

          <Form.Item
            name="status"
            label="文章状态"
            rules={[{ required: true, message: '请选择文章状态' }]}
          >
            <Select placeholder="请选择文章状态">
              <Option value="draft">草稿</Option>
              <Option value="published">已发布</Option>
              <Option value="archived">已归档</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="isTop"
            label="是否置顶"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="isRecommend"
            label="是否推荐"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ArticleManagement;